<template>
  <div class="comment-list">
    <div class="alert alert-danger" v-if="error">{{ error }}</div>
    <div class="alert alert-success" v-if="successMessage">{{ successMessage }}</div>
    
    <div class="filter-bar">
      <div class="filter-dropdown">
        <select v-model="approvedFilter" @change="loadComments">
          <option value="">所有评论</option>
          <option value="true">已审核</option>
          <option value="false">待审核</option>
        </select>
      </div>
    </div>
    
    <div class="data-table">
      <table v-if="comments.length">
        <thead>
          <tr>
            <th>用户</th>
            <th>内容</th>
            <th>文章</th>
            <th>时间</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="comment in comments" :key="comment.id">
            <td class="user-cell">
              <div class="username">{{ comment.username }}</div>
              <div class="email">{{ comment.email }}</div>
            </td>
            <td class="content-cell">{{ comment.content }}</td>
            <td>
              <router-link 
                v-if="comment.article" 
                :to="{ name: 'blog-detail', params: { id: comment.articleId } }"
                target="_blank"
              >
                {{ truncate(comment.article.title, 30) }}
              </router-link>
              <span v-else>未知文章</span>
            </td>
            <td>{{ formatDate(comment.createdAt) }}</td>
            <td>
              <span :class="['status', comment.approved ? 'approved' : 'pending']">
                {{ comment.approved ? '已审核' : '待审核' }}
              </span>
            </td>
            <td class="actions-cell">
              <button 
                v-if="!comment.approved"
                @click="approveComment(comment.id, true)" 
                class="action-btn approve-btn"
                title="批准评论"
              >
                <i class="fas fa-check"></i>
              </button>
              <button 
                v-if="comment.approved"
                @click="approveComment(comment.id, false)" 
                class="action-btn reject-btn"
                title="拒绝评论"
              >
                <i class="fas fa-ban"></i>
              </button>
              <button 
                @click="confirmDelete(comment)" 
                class="action-btn delete-btn"
                title="删除评论"
              >
                <i class="fas fa-trash-alt"></i>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div class="empty-state" v-else>
        <p>暂无评论</p>
      </div>
    </div>
    
    <!-- 删除确认对话框 -->
    <div class="modal" v-if="showDeleteModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>确认删除</h3>
          <button @click="showDeleteModal = false" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <p>确定要删除这条评论吗？</p>
          <div class="comment-preview">
            <div class="comment-author">{{ commentToDelete?.username }}</div>
            <div class="comment-content">{{ commentToDelete?.content }}</div>
          </div>
          <p class="warning">此操作不可恢复！</p>
        </div>
        <div class="modal-footer">
          <button @click="showDeleteModal = false" class="cancel-btn">取消</button>
          <button @click="deleteComment" class="confirm-btn" :disabled="isDeleting">
            {{ isDeleting ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { commentService } from '../../../services';

export default {
  setup() {
    // 状态
    const comments = ref([]);
    const approvedFilter = ref('');
    const error = ref('');
    const successMessage = ref('');
    
    // 删除相关状态
    const showDeleteModal = ref(false);
    const commentToDelete = ref(null);
    const isDeleting = ref(false);
    
    // 加载评论列表
    const loadComments = async () => {
      try {
        error.value = '';
        
        // 构建查询参数
        const params = {};
        if (approvedFilter.value) {
          params.approved = approvedFilter.value;
        }
        
        // 调用API
        const response = await commentService.getAllComments(params);
        comments.value = response.comments || [];
      } catch (err) {
        error.value = '加载评论失败';
        console.error('加载评论失败:', err);
      }
    };
    
    // 审核评论
    const approveComment = async (id, approved) => {
      try {
        error.value = '';
        successMessage.value = '';
        
        await commentService.approveComment(id, approved);
        
        successMessage.value = approved ? '评论已批准' : '评论已拒绝';
        
        // 重新加载评论列表
        await loadComments();
        
        // 3秒后清除成功消息
        setTimeout(() => {
          successMessage.value = '';
        }, 3000);
      } catch (err) {
        error.value = err.response?.data?.message || '操作失败';
        console.error('审核评论失败:', err);
      }
    };
    
    // 确认删除
    const confirmDelete = (comment) => {
      commentToDelete.value = comment;
      showDeleteModal.value = true;
    };
    
    // 删除评论
    const deleteComment = async () => {
      if (!commentToDelete.value) return;
      
      try {
        isDeleting.value = true;
        
        await commentService.deleteComment(commentToDelete.value.id);
        
        // 删除成功
        successMessage.value = '评论删除成功';
        showDeleteModal.value = false;
        
        // 重新加载评论列表
        await loadComments();
        
        // 3秒后清除成功消息
        setTimeout(() => {
          successMessage.value = '';
        }, 3000);
      } catch (err) {
        error.value = err.response?.data?.message || '删除评论失败';
        console.error('删除评论失败:', err);
      } finally {
        isDeleting.value = false;
      }
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    // 截断文本
    const truncate = (text, length) => {
      if (!text) return '';
      return text.length > length ? text.substring(0, length) + '...' : text;
    };
    
    // 初始化
    onMounted(() => {
      loadComments();
    });
    
    return {
      comments,
      approvedFilter,
      error,
      successMessage,
      showDeleteModal,
      commentToDelete,
      isDeleting,
      loadComments,
      approveComment,
      confirmDelete,
      deleteComment,
      formatDate,
      truncate
    };
  }
}
</script>

<style scoped>
.comment-list {
  width: 100%;
}

.filter-bar {
  display: flex;
  margin-bottom: 20px;
}

.filter-dropdown select {
  padding: 10px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 16px;
  min-width: 150px;
}

.data-table {
  margin-bottom: 20px;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e9ecef;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.user-cell {
  min-width: 150px;
}

.username {
  font-weight: bold;
}

.email {
  font-size: 0.85rem;
  color: #6c757d;
}

.content-cell {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
}

.approved {
  background-color: #d4edda;
  color: #155724;
}

.pending {
  background-color: #fff3cd;
  color: #856404;
}

.actions-cell {
  white-space: nowrap;
}

.action-btn {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 5px;
  color: white;
}

.approve-btn {
  background-color: #28a745;
}

.reject-btn {
  background-color: #6c757d;
}

.delete-btn {
  background-color: #dc3545;
}

.approve-btn:hover { background-color: #218838; }
.reject-btn:hover { background-color: #5a6268; }
.delete-btn:hover { background-color: #c82333; }

.empty-state {
  text-align: center;
  padding: 30px;
  color: #6c757d;
}

.alert {
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.alert-danger {
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  color: #721c24;
}

.alert-success {
  background-color: #d4edda;
  border: 1px solid #c3e6cb;
  color: #155724;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 8px;
  width: 100%;
  max-width: 500px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6c757d;
}

.modal-body {
  padding: 20px;
}

.comment-preview {
  margin: 15px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.comment-author {
  font-weight: bold;
  margin-bottom: 5px;
}

.comment-content {
  line-height: 1.5;
}

.warning {
  color: #dc3545;
  font-weight: bold;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #e9ecef;
}

.cancel-btn, .confirm-btn {
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  border: none;
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
}

.confirm-btn {
  background-color: #dc3545;
  color: white;
}

.confirm-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}
</style> 